package com.wdy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private CacheUtil cacheUtil;



    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Override
    @Transactional
    public Result update(Shop shop) {
        //1.判断id是否为空
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        //2.更新数据库
        updateById(shop);
        //3.删除缓存
        stringRedisTemplate.delete("cache:shop:"+shop.getId());
        return Result.ok();
    }





    @Override
    public Result queryById(Long id) {
        //缓存穿透加缓存击穿(逻辑过期)版本
        //Shop shop=cacheUtil.queryByIdWithLogicalExpire(Shop.class, id, "cache:shop:", "lock:shop:",30L, TimeUnit.MINUTES, this::getById);

        //缓存穿透加缓存击穿(互斥锁)版本
        //Shop shop = cacheUtil.queryByIdWithCacheBreakDown(Shop.class, id, "cache:shop:", "lock:shop:",30L, TimeUnit.MINUTES, this::getById);

        //只考虑了缓存穿透版本
        Shop shop = cacheUtil.queryByIdWithCachePenetration(Shop.class, id, "cache:shop:", 30L, TimeUnit.MINUTES, this::getById);
        if(shop== null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }



}
